'use strict';

const { BaseParameter, stateKeys } = require('../core/base_mongo_model');

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const roleSchema = new Schema({
    /**
     * 角色名称
     */
    name: { type: String, default: '' },
    /**
     * 角色描述
     */
    describe: { type: String, default: '' },
    /**
     * 允许访问的界面
     */
    pages: { type: [ String ], default: [] },
    /**
     * 允许访问的接口
     */
    apis: { type: [ String ], default: [] },
    ...BaseParameter,
  });

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 获取所有角色
   */
  roleSchema.statics.findAll = function(field) {
    const params = {
      stateKey: stateKeys.NORMAL,
    };
    const model = this.find(params, field);
    return model.exec();
  };

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 修改角色
   */
  roleSchema.statics.updateWithId = function(id, data) {
    return this.updateOne({
      _id: mongoose.Types.ObjectId(id),
    }, data);
  };

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 删除角色
   */
  roleSchema.statics.removeRole = function(id) {
    return this.deleteOne({
      _id: mongoose.Types.ObjectId(id),
    });
  };

  return mongoose.model('Role', roleSchema, 'roles');
};
